import store from '@/store'

function checkPermission (el, binding) {
  const { value } = binding
  const authes = store.getters && store.getters.menuList

  if (value) {
    const permissions = value instanceof Array ? value : Array.of(value)
    const hasPermission = authes.some(auth => {
      return permissions.includes(auth.key)
    })

    if (!hasPermission) {
      el.parentNode && el.parentNode.removeChild(el)
    }
  } else {
    throw new Error(`need roles! Like v-permission="['admin','editor']"`)
  }
}

export default {
  inserted (el, binding) {
    checkPermission(el, binding)
  },
  update (el, binding) {
    checkPermission(el, binding)
  }
}
